package rpc

import (
	"encoding/json"
	"fmt"
	"go-monitor/common/model"
	"go-monitor/server/g"
	"go-monitor/server/service"
	"os"
)

type Server int

// 请求过来 先用服务器私钥解密   传输时用Agent的公钥加密

// Auth 身份认证
func (c *Server) Auth(req model.AgentAuthRequest, resp *model.SimpleRPCResponse) error {
	if req.ID != "" {
		//1. Agent 请求过来,主动保存Agent的key
		dbkey := "AgentKey_" + req.IP
		_, err := service.Redis.Set(dbkey, string(req.ClientKey), 0)
		if err != nil {
			resp.Code = 1
			resp.Message = "Redis.Set error " + dbkey
			return err
		}

		//2. Redis自动添加未接受状态
		autoKey := "Accept_" + req.IP
		m := make(map[string]interface{})
		m["IsAccept"] = "false"
		m["Ip"] = req.IP
		b, _ := json.Marshal(m)
		_, err = service.Redis.Set(autoKey, string(b), 0)
		if err != nil {
			resp.Code = 1
			resp.Message = "Redis.Set error " + autoKey
			return err
		}

		//3.生成本地文件（去除判断是否本地存在文件, 防止机器重装,使用老的Ip,默认重启Agent就生成一次）
		root, _ := os.Getwd()
		agentauthdir := root + "/var/auth/agent/" + req.IP + ".pem"
		//不存在则生成本地文件
		errauth := service.AuthClientSaveKey(req.ClientKey, agentauthdir)
		if errauth == nil {
			//判断Agent版本是否为最新版本
			if req.AgentVersion == g.Config().AgentVersion {
				resp.Code = 0
				resp.Message = "ok"
			} else {
				resp.Code = 1
				resp.Message = "versions are different"
			}
		} else {
			resp.Code = 1
			resp.Message = "creat client public key fail"
		}
	} else {
		resp.Code = 1
		resp.Message = "request IP is empty"
	}

	return nil
}

// ReportStatus 心跳数据
func (c *Server) ReportStatus(req model.AgentReportRequest, resp *model.SimpleRPCResponse) error {
	// dbKey := "report_status_" + req.IP
	// result, err := json.Marshal(req)
	// if err != nil {
	// 	resp.Code = 1
	// 	resp.Message = "json.Marshal error"
	// 	g.Logger.Error("json.Marshal error：", err)
	// 	return err
	// }
	// _, err = service.Redis.Set(dbKey, string(result), 0)
	// if err != nil {
	// 	resp.Code = 1
	// 	resp.Message = "Redis1.Set:" + dbKey + " error"
	// 	g.Logger.Error("Redis1.Set:"+dbKey+" error：", err)
	// 	return err
	// }
	fmt.Println("心跳数据：", req)
	resp.Code = 0
	resp.Message = "ok"
	return nil
}
